// pages/fightGroup/fightGroup.js
const teamBuyService = require('../../../../api/teamBuyService.js')
const util = require('../../../../utils/utils.js')
//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    storeName: '',
    storeId: '',
    groupTimeId: ''
  },

  // 跳转到商品详情页面
  toGoodsDetail: function (val) {
    console.log(val)
    const that = this
    let teamBuyId = val.currentTarget.dataset.teambuyid
    let mobile = ''
    if (that.options.mobile) {
      mobile = that.options.mobile
    }
    wx.navigateTo({
      url: '../../goods/goodsDetail/goodsDetail?productId=' + teamBuyId + '&storeId=' + that.data.storeId + '&type=group' + '&mobile=' + mobile
    })
  },
  queryTeamBuyingList: function (storeId) {
    const self = this
    console.log(storeId)
    let teamBuyingList = []
    teamBuyService.getStartedTeamBuyingByStoreId(storeId).then(res => {
      console.log(res)
      if (res) {
        res.forEach(item => {
          let tempItem = {
            id: item.id,
            name: item.name,
            description: item.description ? item.description : '',
            nowPrice: item.teamLeaderPrice ? item.teamLeaderPrice : item.teamMemberPrice,
            oldPrice: item.originalPrice ? item.originalPrice : '',
            img: item.picture ? item.picture : '',
            productId: item.productId,
            teamMemberCount: item.teamMemberCount,
            memberCount: util.numberConversion.numberToChinese(item.teamMemberCount)
          }
          if (item.teamMemberCount === 3) {
            tempItem = {
              ...tempItem,
              color: '#ff7d51',
            }
          } else if (item.teamMemberCount === 5) {
            tempItem = {
              ...tempItem,
              color: '#019f55',
            }
          }
          teamBuyingList.push(tempItem)
        });
        self.setData({
          list: teamBuyingList
        })
        self.getGroupActivityCountDown(res)
      } else {

      }
    })
  },
  // 获取团购活动倒计时
  getGroupActivityCountDown: function (groupList) {
    const that = this
    let tempGroupList = that.data.list
    let timeArr = []
    if (groupList.length > 0) {
      groupList.forEach(item => {
        let startTime = item.startTime
        let endTime = item.endTime
        let startTimeStamp = new Date(startTime.replace(/-/g, '/')).getTime()
        let endTimeStamp = new Date(endTime.replace(/-/g, '/')).getTime()
        let duration = (endTimeStamp - startTimeStamp) / 1000
        timeArr.push({
          openTeamTime: startTime,
          duration: duration
        })
      })
    }
    countDown()
    // 执行倒计时函数
    function countDown() {
      clearTimeout(that.data.groupTimeId)
      let newArr = []
      let timeList = util.countDownDay(timeArr)
      for (let i = 0; i < tempGroupList.length; i++) {
        const element = tempGroupList[i];
        let tempItem = {
          ...element,
          days: parseInt(timeList[i].day) + 1
        }
        newArr.push(tempItem)
      }
      var time = setTimeout(
        function () {
          countDown(timeArr);
        }, 1000)
      that.setData({
        groupTimeId: time,
        list: newArr
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    this.getMemberUserInfo()
    const self = this;
    // 判断globalData.storeInfo有没有数据，有数据，则使用选择的门店数据，没有，则根据当前地理位置获取最近门店
    if (app.globalData.storeInfo) {
      self.setData({
        storeName: app.globalData.storeInfo.name,
        storeId: app.globalData.storeInfo.id,
      })
      this.queryTeamBuyingList(app.globalData.storeInfo.id)
    } else {
      // 获取当前地理位置，然后筛选出最近的门店，根据当前门店获取门店的商品
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          var latitude = res.latitude
          var longitude = res.longitude
          var speed = res.speed
          var accuracy = res.accuracy
          try {
            var tempAllStores = wx.getStorageSync('wj_allStores'); // 获取缓存的所有门店
            if (tempAllStores) {
              // Do something with return value
              let tempIndex = self.getNearestStore(tempAllStores, latitude, longitude);
              app.globalData.storeInfo = tempAllStores[tempIndex];
              // 获取当前门店的所有分类和商品
              self.queryTeamBuyingList(tempAllStores[tempIndex].id)
            } else {
              // 查询所有门店
              storeService.queryList().then(res => {
                var allStores = res;
                try {
                  wx.setStorageSync('wj_allStores', allStores)
                } catch (e) {
                  console.log(e)
                }
                let tempIndex = self.getNearestStore(allStores, latitude, longitude);
                return allStores[tempIndex]
              }).then(res => {
                app.globalData.storeInfo = res;
                self.queryTeamBuyingList(res.id)
              })
            }
          } catch (e) {
            // Do something when catch error
          }
        }
      })
    }
    if (options.scene) {
      var scene = decodeURIComponent(options.scene)
      try {
        wx.setStorageSync('wj_sharingId', scene)
      } catch (e) {}
    }
    if (self.options.mobile && self.options.mobile != '' && self.options.mobile != undefined) {
      const mobile = self.options.mobile
      try {
        wx.setStorageSync('wj_sharingId', mobile)
      } catch (e) {}
    }
  },
  // 点击切换门店
  changeStore: function () {
    wx.navigateTo({
      url: '../../index/selectStore/selectStore'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.storeInfo) {
      this.setData({
        storeName: app.globalData.storeInfo.name,
        storeId: app.globalData.storeInfo.id
      })
      this.queryTeamBuyingList(this.data.storeId)
    }
  },
  // 获取最近的一家门店
  getNearestStore: function (allStores, latitude, longitude) {
    var distanceArr = [];
    allStores.forEach(item => {
      let dis = util.distance(latitude, longitude, item.latitude, item.longitude);
      distanceArr.push(dis);
    })
    // 计算最小值
    const minN = Math.min.apply(Math, distanceArr);
    let tempIndex = 0;
    for (var i = 0; i < distanceArr.length; i++) {
      if (minN === distanceArr[i]) {
        tempIndex = i;
        break;
      }
    }
    this.setData({
      storeName: allStores[tempIndex].name,
      storeId: allStores[tempIndex].id
    })
    return tempIndex;
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearTimeout(this.data.groupTimeId)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(this.data.groupTimeId)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      let memberId = app.globalData.userInfo.member.id
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/fightGroup/fightGroup/fightGroup?mobile=' + memberId,
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        }
      }
    } else {
      return {
        title: '无界门店商城让生活更便利',
        path: '/pages/mallModule/fightGroup/fightGroup/fightGroup',
        imageUrl: 'https://app-1256684088.cos.ap-beijing.myqcloud.com/wujieImages/iconCover(1).png',
        success(e) {
          wx.showShareMenu({
            withShareTicket: true
          })
        }
      }
    }
  },
  // 前往首页
  toHome: function () {
    wx.switchTab({
      url: '../index/index'
    })
  },
  // 获取缓存的用户信息
  getMemberUserInfo: function () {
    if (!app.globalData.userInfo) {
      wx.showToast({
        title: "您还未授权，请登陆授权",
        icon: 'none',
        duration: 2000
      })
    } else {

    }
  },
  // 用户登录组件事件处理
  handleUserLogin: function () {
    console.log(app.globalData.userInfo)
    const self = this
    if (app.globalData.userInfo) {
      const user = app.globalData.userInfo
      this.setData({
        userInfo: {
          ...user.wxaUser
        }
      })
      if (app.globalData.userInfo.member) {
        self.setData({
          hasUserInfo: true,
        })
      } else {
        self.setData({
          userInfo: user.wxaUser,
          hasUserInfo: true,
        })
      }
    }
  },
  handleTabbar: function (e) {
    console.log(e.detail)
    if (e.detail.showTabbar === true) {
      this.setData({
        showTabbar: e.detail.showTabbar
      })
    } else {
      this.setData({
        showTabbar: e.detail.showTabbar
      })
    }
  }
})